package com.atguigu.yygh.msm.controller;


import com.atguigu.yygh.common.result.R;
import com.atguigu.yygh.msm.service.MsmService;

import com.atguigu.yygh.msm.utils.RandomUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/api/msm")
public class MsmController {

    @Autowired
    private MsmService msmService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @GetMapping(value = "/send/{phone}")
    public R code(@PathVariable String phone) {

        String code = redisTemplate.opsForValue().get(phone);
        if (!StringUtils.isEmpty(code)) return R.ok();

        code = RandomUtil.getFourBitRandom();
        Map<String, Object> param = new HashMap<>();
        param.put("code",code);

        //发送短信
        boolean isSend = msmService.sendMessage(phone, code);
        if (isSend){
            //发送成功  redis中存储数据
            redisTemplate.opsForValue().set(phone,code,50, TimeUnit.DAYS);
            return R.ok();
        }else {
            return R.error().message("发送短信失败");
        }
    }


}
